import { verifyAccessToken } from '@@/server/utils/jwt';

export default defineNitroPlugin((nitroApp) => {
    nitroApp.hooks.hook('request', async (event) => {
        // 排除不需要认证的路由
        const publicPaths = ['/api/auth/login', '/api/auth/refresh'];
        const path = event.node.req.url || '';
        
        // 只处理 API 路由，且不在公开路径列表中
        if (!/^\/api/.test(path) || publicPaths.some(publicPath => path.includes(publicPath))) {
            return;
        }

        // 从请求头获取 token
        const authHeader = getHeader(event, 'authorization');
        
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            throw createError({
                statusCode: 401,
                message: '未提供认证 token',
            });
        }

        const token = authHeader.substring(7); // 移除 "Bearer " 前缀

        try {
            // 验证 token 并将用户信息添加到 event context
            const payload = verifyAccessToken(token);
            event.context.user = payload;
        } catch (error: any) {
            throw createError({
                statusCode: 401,
                message: '无效的 token',
            });
        }
    });
});